package com.shujia.wyh.mysql_jdbc;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.*;
import java.util.Properties;

/*
    使用配置文件存储基本信息
 */
public class JDBCDemo3 {
    public static void main(String[] args) {
        Connection conn = null;
        Statement statement = null;
        try {
            //创建一个配置文件对象
            Properties prop = new Properties();
            //加载配置文件
            prop.load(new BufferedReader(new FileReader("src/com/shujia/wyh/mysql_jdbc/mysqlinfo.properties")));
            //根据key获取对应的value值
            String url = prop.getProperty("url");
            String user = prop.getProperty("user");
            String password = prop.getProperty("password");

            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");

            //获取连接对象
            conn = DriverManager.getConnection(url, user, password);
            //获取操作数据库对象
            statement = conn.createStatement();

            //编写sql语句
            String sql = "select deptno as d_wyj,dname,loc from dept";

            //执行sql语句
            //executeQuery执行查询语句
            //executeUpdate执行增删改语句
            //返回的是一个查询结果集对象，存储着数据
            ResultSet resultSet = statement.executeQuery(sql);
//            boolean next = resultSet.next(); //返回结果如果是true表示有数据
////            System.out.println(next);
//            String id = resultSet.getString("deptno");
//            System.out.println(id);
//
//            String dname = resultSet.getString("dname");
//            System.out.println(dname);
//
//            String loc = resultSet.getString("loc");
//            System.out.println(loc);

            //使用while循环改进
            while (resultSet.next()) {
                //根据列名获取列值,如果查询语句最终列名有别名的话，获取列值的时候，是根据别名获取
                String id = resultSet.getString("d_wyj");
                String dname = resultSet.getString("dname");
                String loc = resultSet.getString("loc");
                System.out.println("部门编号：" + id + "，部门名称：" + dname + "，部门地址：" + loc);

                //根据列的索引获取
//                String id = resultSet.getString(1);
//                String dname = resultSet.getString(2);
//                String loc = resultSet.getString(3);
//                System.out.println("部门编号：" + id + "，部门名称：" + dname + "，部门地址：" + loc);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
